package net.address;
import content.ContentManager;
import js.Lib;
import params.GlobalParams;

/**
 * @author PRASS
 */

class Address 
{
	
	
	static private var _callBacks	: Array<Dynamic>;
	
	static private var _hash		: String;
	static private var _ref			: Dynamic;
	static private var _callBack	: Dynamic;
	
	static private var _autoChangeAllowed : Bool;
	
	public function new()
	{

	}
	
	static public function init( ref : Dynamic, callBack : Dynamic ) : Void
	{
		if( _callBacks == null ) _callBacks = new Array<Dynamic>();
		
		//_ref = ref;
		//_callBack = callBack;
		_callBacks.push(callBack);
		_autoChangeAllowed = false;
		
		untyped Lib.window.onhashchange = function() { onChange(); };
		
		onChange();
	}
	
	static public function goto( hash : String, trustedID : Bool = false ) : Void
	{
		_hash = hash;
		
		_autoChangeAllowed = true;
		Lib.window.location.href = _hash;
	}
	
	static public function onChange() : Void
	{
		if ( _autoChangeAllowed == false ) _hash = getHref();
		
		//Reflect.callMethod( _ref, _callBack, [_hash]);
		//_callBack(_hash);
		var i : Int = 0;
		while ( i < _callBacks.length)
		{
			_callBacks[i](_hash);
			i++;
		}
		
		_autoChangeAllowed = false;
	}
	
	static public function addCallBack( fn : Dynamic ) : Void
	{
		if( _callBacks == null ) _callBacks = new Array<Dynamic>();
		
		_callBacks.push(fn);
	}
	
	static private function getHref () : String
	{
		var hash : String = "";
		
		if ( Lib.window.location.href.split("#")[1] != null )
			hash = "#" + Lib.window.location.href.split("#")[1];
		
		return hash;
	}
	
}